package com.module.codeBind.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import base.common.CUDEnum;
import base.dao.GenericHibernateDao;
import base.util.JsonMsg;
import base.util.Page;
import base.util.StringUtil;
import base.util.Tools;
import base.util.datetime.DateTimeUtil;

import com.module.codeBind.common.CodeBindConstant;
import com.module.codeBind.vo.BatchCode;
import com.module.codeBind.vo.BatchCodeItem;
import com.module.codeBind.vo.BatchCodeSyn;



public class BatchCodeDao  extends GenericHibernateDao<BatchCode,String> implements CodeBindConstant{
	private static BatchCodeDao dao = new BatchCodeDao();
	private static BatchCodeItemDao itemDao = BatchCodeItemDao.getInstance();
	private static BatchCodeSynDao batchCodeSynDao =BatchCodeSynDao.getInstance();
	private static BatchCodeItemSynDao batchCodeItemSynDao = BatchCodeItemSynDao.getInstance();
	
	private BatchCodeDao(){}
	public static BatchCodeDao getInstance(){
		return dao;
	}
	public JsonMsg saveBatchCode(Session session,BatchCode code){	

		JsonMsg verifyJsonMsg = itemDao.verify(session,code.getItems(),code.getId());
		if(!verifyJsonMsg.getState()){
			return verifyJsonMsg;
		}else{
			JsonMsg jsonMsg = new JsonMsg(true);
			String batchCodeId = code.getId();
			boolean flag = false;
			if(Tools.isValid(code.getId())){
				//添加BatchCodeSyn增量表操作记录
				BatchCode codeEld = this.findById(session, code.getId());
				flag = batchCodeSynDao.updateBatchCodeSyn(session, codeEld, code);
				session.clear();
				session.update(code);
			}else {
				batchCodeId = (String)session.save(code);
				//添加BatchCode增量表操作记录
				try{
					BatchCodeSyn batchCodeSyn = new BatchCodeSyn();
					PropertyUtils.copyProperties(batchCodeSyn,code);//对比数据，并构建目标对象
					batchCodeSyn.setSyscStatus(CUDEnum.C.toString());
					flag = batchCodeSynDao.saveBatchCodeSyn(session, batchCodeSyn);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			List<BatchCodeItem> eldCodeItem = itemDao.listByProperty(session, "batchCodeId", batchCodeId);
			List<String> eldCodeItemId = new ArrayList<String>();//原纪录的主键id
			for(BatchCodeItem item:eldCodeItem){
				eldCodeItemId.add(item.getId());
			}
			itemDao.save(session,code.getItems(), batchCodeId);

			//添加BatchCodeItem增量表操作记录
			batchCodeItemSynDao.saveCodeItemSyn(session, code.getItems(),eldCodeItemId, batchCodeId);
			
			jsonMsg.setSuccessMsg("\u4fdd\u5b58\u6210\u529f");//保存成功
			return jsonMsg;
		}	
	}
	/**
	 * 查询贴码信息列表
	 * @param session
	 * @param bean
	 * @param rollNum
	 * @param sequenceNum
	 * @param start
	 * @param limit
	 * @return
	 */
	public Page getList(Session session, BatchCode bean,String rollNum,Integer sequenceNum, Integer start, Integer limit) {
		System.err.println(bean.getIsBindApp());
		Page page = new Page();
		page.setStart(start);
		page.setLimit(limit);
		StringBuffer sb = new StringBuffer();
		StringBuffer condition = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		if (Tools.isValid(bean.getProductId())) {
			condition.append(" and obj.productId = ?");
			params.add(bean.getProductId());
		}
		if (Tools.isValid(bean.getBatchNo())) {
			condition.append(" and obj.batchNo like '%").append(bean.getBatchNo()).append("%'");
		}
		if (Tools.isValid(bean.getProductionDate())) {
			condition.append(" and obj.productionDate >= ?");
			params.add(DateTimeUtil.adjustStartDate(bean.getProductionDate()));
		}
		if (Tools.isValid(bean.getProductionDateEnd())) {
			condition.append(" and obj.productionDate <=?");
			params.add(DateTimeUtil.adjustEndDate(bean.getProductionDateEnd()));
		}
		if (Tools.isValid(bean.getBatchCodeState())) {
			condition.append(" and obj.batchCodeState =?");
			params.add(bean.getBatchCodeState());
		}
		if (Tools.isValid(bean.getOpenType())) {
			condition.append(" and obj.openType =?");
			params.add(bean.getOpenType());
		}
		
		if (Tools.isValid(rollNum) && Tools.isValid(sequenceNum)) {
			condition.append(" and bci.volumeNo ='").append(rollNum).append("'");
			//params.add(rollNum);
			condition.append(" and bci.startSeq >=").append(sequenceNum).append(" and bci.endSeq <=" ).append(sequenceNum);
			//params.add(sequenceNum);
			//params.add(sequenceNum);
		}
		sb.append("select distinct obj from BatchCode as obj,BatchCodeItem as bci where 1=1");
		if (Tools.isValid(bean.getIsBindApp())) {
			if(bean.getIsBindApp().intValue()==1){
				sb.append(" and obj.id ");
			}else if(bean.getIsBindApp().intValue()==-1){
				sb.append(" and obj.id not ");
			}
			sb.append("in (select bbc.batchCodeId from BindBatchCode as bbc where obj.id = bbc.batchCodeId)");
		}
		sb.append(" and obj.id=bci.batchCodeId");
		sb.append(" and obj.status !='"+CUDEnum.D.toString()+"'" );
		sb.append(" and obj.orgId in ("+bean.getOrgId()+")");
		sb.append(condition);
		Query query = session.createQuery(sb.toString());
		int i = 0;
		for (Object obj : params) {
			query.setParameter(i, obj);
			i++;
		}
		StringBuffer countHql = new StringBuffer();
		countHql.append("select count(*) from BatchCode as obj,BatchCodeItem as bci where 1=1");
		if (Tools.isValid(bean.getIsBindApp())) {
			if(bean.getIsBindApp().intValue()==1){
				countHql.append(" and obj.id ");
			}else if(bean.getIsBindApp().intValue()==-1){
				countHql.append(" and obj.id not ");
			}
			countHql.append("in (select bbc.batchCodeId from BindBatchCode as bbc where obj.id = bbc.batchCodeId)");
		}
		countHql.append(" and obj.id=bci.batchCodeId");
		countHql.append(" and obj.status !='"+CUDEnum.D.toString()+"'" );
		countHql.append(" and obj.orgId in ("+bean.getOrgId()+")");
		countHql.append(condition);
		query.setFirstResult(start).setMaxResults(limit);
		Query totalQuery = session
				.createQuery(countHql.toString());
		int j = 0;
		for (Object obj : params) {
			totalQuery.setParameter(j, obj);
			j++;
		}
		page.setTotal((long) ((Long) totalQuery.uniqueResult()).intValue());
		page.setRows(query.list());
		return page;
	}
	public List getList(Session session,BatchCode bean,String bindId) {
		
		StringBuffer sb = new StringBuffer();
		StringBuffer condition = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		if (Tools.isValid(bean.getProductId())) {
			condition.append(" and obj.productId = ?");
			params.add(bean.getProductId());
		}
		sb.append("select obj from BatchCode as obj ");
		sb.append(" where obj.id not in (select ebbc.batchCodeId from BindBatchCode as ebbc, CodeBind as eb where ebbc.bindId=eb.id and eb.status !='"+CUDEnum.D.toString()+"'" );
		if(Tools.isValid(bindId)){
		 sb.append(" and  eb.id !='"+bindId+"'");
		}
		sb.append(") and 1=1 and obj.status !='"+CUDEnum.D.toString()+"'" );
		
		sb.append(condition);
		Query query = session.createQuery(sb.toString());
		int i = 0;
		for (Object obj : params) {
			query.setParameter(i, obj);
			i++;
		}
		Query totalQuery = session
				.createQuery("select count(*) from BatchCode as obj where 1=1 and obj.status !='"+CUDEnum.D.toString()+"'"
						+ condition);
		int j = 0;
		for (Object obj : params) {
			totalQuery.setParameter(j, obj);
			j++;
		}
		return query.list();
	}
	public BatchCode findById(Session session,String id){
		BatchCode bean =  this.get(session,id);
		Query itemQuery = session
		.createQuery("select obj from BatchCodeItem as obj where 1=1 and obj.batchCodeId='"+id+"'");
		bean.setItems(itemQuery.list());
		return bean;
	}
	/**
	 * 删除贴码信息
	 * @param session
	 * @param list
	 * @param updateId
	 * @return
	 */
	public int deleteBatchCode(Session session,final List list,String updateId){
		final String hqlUpdate = "update BatchCode set status = ? ,updaterId=?, updateTime=? where id in ("+StringUtil.getNewStrByList(list)+")";
				Query query = session.createQuery(hqlUpdate);
				query.setParameter(0, CUDEnum.D.toString());
				query.setParameter(1, updateId);
				query.setParameter(2, new Date());
				int updatedEntities = query.executeUpdate();
				//添加BatchCode操作记录
				boolean flag = false;
				for(int i=0;i<list.size();i++){
					String id = (String)list.get(i);
					BatchCodeSyn batchCodeSyn = new BatchCodeSyn();
					batchCodeSyn.setId(id);
					batchCodeSyn.setStatus(CUDEnum.D.toString());
					batchCodeSyn.setUpdaterId(updateId);
					batchCodeSyn.setUpdateTime(new Date());
					batchCodeSyn.setSyscStatus(CUDEnum.D.toString());
					flag = batchCodeSynDao.saveBatchCodeSyn(session, batchCodeSyn);
				}
				
				return updatedEntities;
	}
	/**
	 * 开启手工类型的批次
	 * @param list Id集
	 * @return 成功或者失败
	 */
	public boolean openBatchByHand(Session session,final List<String> list){
		boolean flag = false;
		final String hql = "update BatchCode set batchCodeState = ?,openTime=? where id in ("+StringUtil.getNewStrByList(list)+")";
			Query query = session.createQuery(hql);
			query.setParameter(0, BATCH_CODE_OPENED);
			query.setParameter(1, new Date());
			query.executeUpdate();
			
			//添加BatchCode操作记录
			for(int i=0;i<list.size();i++){
				String id = (String)list.get(i);
				BatchCodeSyn batchCodeSyn = new BatchCodeSyn();
				batchCodeSyn.setId(id);
				batchCodeSyn.setBatchCodeState(BATCH_CODE_OPENED);
				batchCodeSyn.setOpenTime(new Date());
				batchCodeSyn.setSyscStatus(CUDEnum.U.toString());
				flag = batchCodeSynDao.saveBatchCodeSyn(session, batchCodeSyn);
			}

		 return flag;
	}
	
	/**
	 * 开启定时类型的批次
	 * @return 成功或者失败
	 * @author dengsq
	 */
	public boolean openBatchByTime(Session session){
		Transaction tx = null;
		String hql = "update  BatchCode set batchCodeState = ? where openType=? and openTime=? and batchCodeState =  ?";
		String hqlf="from BatchCode where openType="+OPEN_TYPE_TIME+" and openTime='"+DateTimeUtil.adjustStartDate(new Date())+"'  and batchCodeState ="+BATCH_CODE_NOT_OPENED;
		boolean flag = false;
		try{
			List<BatchCode> batchCodes = this.findBySQL(session, hqlf);
			for(int i=0;i<batchCodes.size();i++){
				BatchCodeSyn batchCodeSyn = new BatchCodeSyn();
				batchCodeSyn.setId(batchCodes.get(i).getId());
				batchCodeSyn.setBatchCodeState(BATCH_CODE_OPENED);	
				batchCodeSyn.setOrgId(batchCodes.get(i).getOrgId());
				batchCodeSyn.setSyscStatus(CUDEnum.U.toString());
				flag = batchCodeSynDao.saveBatchCodeSyn(session, batchCodeSyn);
			}
	    	Query query = session.createQuery(hql);
	    	query.setParameter(0, BATCH_CODE_OPENED).setParameter(1, OPEN_TYPE_TIME).
	    	setParameter(2, DateTimeUtil.adjustStartDate(new Date())).setParameter(3, BATCH_CODE_NOT_OPENED);
	    	query.executeUpdate();
	        flag = true;
		    return flag;
		}catch (Exception ex) {
	    	ex.printStackTrace();
		    return flag;
	    }
	}	
}
